﻿//https://leetcode.cn/problems/minimum-operations-to-reduce-x-to-zero/
//我的
class Solution {
public:
    int minOperations(vector<int>& nums, int x) {
        //将求左右随机区域之和为x -> 求(最长)中间区域之和为sum - x      
        int sum = 0;
        for (auto t : nums)
        {
            sum += t;
        }
        int realValue = sum - x;
        if (realValue < 0)return -1;
        int sz = nums.size();
        int tmp = 0, ret = INT_MAX;
        for (int left = 0, right = 0; left < sz; ++left)
        {
            //小于右加
            while (right < sz && tmp < realValue)
            {
                tmp += nums[right];
                ++right;
            }

            //达到条件 -> 筛选最小操作数
            if (tmp == realValue)
            {
                ret = min(ret, sz - (right - left));
            }

            //大于左减
            tmp -= nums[left];
        }
        return ret == INT_MAX ? -1 : ret;
    }

};
//答案
class Solution
{
public:
	int minOperations(vector<int>& nums, int x)
	{
		int sum = 0;
		for (int a : nums) sum += a;
		int target = sum - x;
		// 细节问题
		if (target < 0) return -1;
		int ret = -1;
		for (int left = 0, right = 0, tmp = 0; right < nums.size(); right++)
		{
			tmp += nums[right]; // 进窗⼝
			while (tmp > target) // 判断
				tmp -= nums[left++]; // 出窗⼝
			if (tmp == target) // 更新结果
				ret = max(ret, right - left + 1);
		}
		if (ret == -1) return ret;
		else return nums.size() - ret;
	}
};